/**
 * 视频路由模块
 * @author HalRui
 * @version 1.0.0
 * @description 定义视频相关的API接口，包括视频上传、查询、更新、删除、搜索等功能
 * @date 2025年9月27日
 */

const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const {uploads} = require('../../env.config.json');
const STATUS_CODES = require('../../utils/status-codes');
const videoAPI = require('../../libs/videos-api');
// Removed unused import: const {locals} = require("express/lib/application");


router.post('/upload-chunk',(req,res)=>{
    const {fromid,nowNum , total ,filename} = req.fields;
    const {video} = req.files;

    //1.生成视频上传的 根路径
    const rootPath = path.join(__dirname,"../../",uploads.videos);

    //2.检测是否存在 用户 userId 命名的 目录
    const userPath = path.join(rootPath,fromid);
    //如果用户目录不存在,则创建
    const isExists = fs.existsSync(userPath);

    if(!isExists){//不存在则创建
        fs.mkdirSync(userPath, { recursive: true });
    }
    //3.拼接路径
    const filepath = path.join(userPath,`${path.basename(filename)}-${total}-${nowNum}-${path.extname(filename)}`);

    //4.把临时上传 位置的路径 移动 到 拼接路径中
    console.log(`uploading ${video.path}`);
    try{
        fs.copyFileSync(video.path,filepath);
        fs.unlinkSync(video.path);
    }catch(err){
        return res.json({
            code : STATUS_CODES.UPLOAD_ERROR.code,
            msg : STATUS_CODES.UPLOAD_ERROR.message,
        });
    }

    res.json({
        code : 0,
        msg : `总共${total}文件树,当前第${nowNum}上传成功`
    })
})

router.post('/merge-chunk',async (req,res)=>{

    const {fromid,title,isduet,type,desc,filename,total} = req.fields;



    //1.生成视频上传的 根路径
    const rootPath = path.join(__dirname,"../../",uploads.videos);



    //2.检测是否存在 用户 userId 命名的 目录
    const userPath = path.join(rootPath,fromid);

    //如果用户目录不存在,则创建
    const isExists = fs.existsSync(userPath);

    if(!isExists){//不存在则创建
        fs.mkdirSync(userPath, { recursive: true });
    }
    //准备一个文件合并好以后得名称或者路径
    const filepath = path.join(userPath,`${path.basename(filename)}-${Date.now()}-${path.extname(filename)}`)
    //3.拼接路径
    try{
        for (let i = 1; i <= total ; i++) {
            //合并文件
            const fp = path.join(userPath,`${path.basename(filename)}-${total}-${i}-${path.extname(filename)}`);
            //将 碎片文件 写入到 完整的文件当中
            const rs = fs.createReadStream(fp);
            const ws = fs.createWriteStream(filepath, { flags: 'a' });
            rs.pipe(ws);

            ws.on('finish', () => {
                //删除碎片文件
                try{
                    fs.unlinkSync(fp);
                }catch(err){
                    console.log(2);
                }
            })
        }
    }catch(err){
        console.log(1);
    }

    //入库

    const result = await videoAPI.publishVideo({
        fromID : fromid,
        isduet,
        title,
        content : desc,
        type,
        path : filepath
    })

    if(result.success){
        res.json({
            code : STATUS_CODES.SUCCESS.code,
            msg : "视频发布成功",
        });
    }else{
        res.json({
            code : STATUS_CODES.PULISH_ERROR.code,
            msg : STATUS_CODES.PULISH_ERROR.message
        })
    }
})

router.post('/upload-video', function(req,res,next){
        //uploads/vidos/email|userId/a.mp4
        //网络不好 , 磁盘不够 , 内容敏感 , 字幕检测
        const {fromid,title} = req.fields;
        const {video} = req.files;

        if(video.size === 0){//判断是否上传
            return res.json({
                code : STATUS_CODES.NO_VIDEO_UPLOADED.code,
                msg : STATUS_CODES.NO_VIDEO_UPLOADED.message,
            })
        }

        //本地存储对象
        req.locals = {
            success : false,  //没有上传成功
            videoPath : '',
        };

        //1.生成视频上传的 根路径
        const rootPath = path.join(__dirname,"../../",uploads.videos);

        //2.检测是否存在 用户 userId 命名的 目录
        const userPath = path.join(rootPath,fromid);
        //如果用户目录不存在,则创建
        const isExists = fs.existsSync(userPath);

        if(!isExists){//不存在则创建
            fs.mkdirSync(userPath, { recursive: true });
        }
        //3.拼接路径

        //video.path
        const filepath = path.join(userPath,`${fromid}-${title}-${Date.now()}-${path.extname(video.name)}`);

        //4.把临时上传 位置的路径 移动 到 拼接路径中
        try{
            fs.renameSync(video.path,filepath);
            req.locals.success = true;       //上传成功了
            req.locals.videoPath = filepath;  //上传视频的路径
        }catch(err){
            return res.json({
                code : STATUS_CODES.UPLOAD_ERROR.code,
                msg : STATUS_CODES.UPLOAD_ERROR.message,
            });
        }

        next();
    },
    async (req, res) => {
        const {fromid , isduet , title , content ,type } =  req.fields;

        const {success , videoPath} = req.locals;

        // 5.等视频上传成功了, 在存储信息进入到 mongo 中
        // 将绝对路径转换为相对于public目录的路径，用于Web访问
        const relativePath = path.relative(path.join(__dirname, '../../public'), videoPath).replace(/\\/g, '/');
        const webPath = '/' + relativePath;
        
        const result = await videoAPI.publishVideo({
            fromID : fromid,
            isduet,
            title,
            content,
            type,
            path : webPath
        })

        if(result.success){
            res.json({
                code : STATUS_CODES.SUCCESS.code,
                msg : "视频发布成功",
            });
        }else{
            res.json({
                code : STATUS_CODES.PULISH_ERROR.code,
                msg : STATUS_CODES.PULISH_ERROR.message
            })

            fs.unlinkSync(req.locals.filePath);
        }
    });

// 获取视频列表
router.get('/list', async (req, res) => {
    try {
        const { page = 1, limit = 20, sortBy = 'createAt', sortOrder = 'desc', category, userId } = req.query;
        
        const result = await videoAPI.getVideoList({
            page: parseInt(page),
            limit: parseInt(limit),
            sortBy,
            sortOrder,
            category,
            userId
        });
        
        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: '获取视频列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取视频列表失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR,
            message: '获取视频列表失败',
            error: error.message
        });
    }
});

// 获取视频详情
router.get('/detail/:videoId', async (req, res) => {
    try {
        const { videoId } = req.params;
        const { viewerId } = req.query; // 可选的观看者ID，用于记录观看历史
        
        if (!videoId) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR.code,
                message: '视频ID不能为空'
            });
        }
        
        const video = await videoAPI.getVideoDetail(videoId, viewerId);
        
        if (!video) {
            return res.status(404).json({
                code: STATUS_CODES.NOT_FOUND.code,
                message: '视频不存在'
            });
        }
        
        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: '获取视频详情成功',
            data: video
        });
    } catch (error) {
        console.error('获取视频详情失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: '获取视频详情失败',
            error: error.message
        });
    }
});

// 搜索视频
router.get('/search', async (req, res) => {
    try {
        const { keyword, page = 1, limit = 20, sortBy = 'createAt', sortOrder = 'desc' } = req.query;
        
        if (!keyword || keyword.trim() === '') {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '搜索关键词不能为空'
            });
        }
        
        const result = await videoAPI.searchVideos({
            keyword: keyword.trim(),
            page: parseInt(page),
            limit: parseInt(limit),
            sortBy,
            sortOrder
        });
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '搜索视频成功',
            data: result
        });
    } catch (error) {
        console.error('搜索视频失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR,
            message: '搜索视频失败',
            error: error.message
        });
    }
});

// 更新视频信息
router.put('/update/:videoId', async (req, res) => {
    try {
        const { videoId } = req.params;
        const { userId, title, description, category, tags, privacy } = req.body;
        
        if (!videoId || !userId) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR.code,
                message: '视频ID和用户ID不能为空'
            });
        }
        
        const updateData = {};
        if (title !== undefined) updateData.title = title;
        if (description !== undefined) updateData.description = description;
        if (category !== undefined) updateData.category = category;
        if (tags !== undefined) updateData.tags = tags;
        if (privacy !== undefined) updateData.privacy = privacy;
        
        const result = await videoAPI.updateVideo(videoId, userId, updateData);
        
        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: '更新视频信息成功',
            data: result
        });
    } catch (error) {
        console.error('更新视频信息失败:', error);
        if (error.message === '视频不存在') {
            res.status(404).json({
                code: STATUS_CODES.NOT_FOUND.code,
                message: error.message
            });
        } else if (error.message === '无权限修改此视频') {
            res.status(403).json({
                code: STATUS_CODES.FORBIDDEN.code,
                message: error.message
            });
        } else {
            res.status(500).json({
                code: STATUS_CODES.SERVER_ERROR.code,
                message: '更新视频信息失败',
                error: error.message
            });
        }
    }
});

// 删除视频
router.delete('/delete/:videoId', async (req, res) => {
    try {
        const { videoId } = req.params;
        const { userId } = req.body;
        
        if (!videoId || !userId) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR.code,
                message: '视频ID和用户ID不能为空'
            });
        }
        
        const result = await videoAPI.deleteVideo(videoId, userId);
        
        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: '删除视频成功',
            data: result
        });
    } catch (error) {
        console.error('删除视频失败:', error);
        if (error.message === '视频不存在') {
            res.status(404).json({
                code: STATUS_CODES.NOT_FOUND.code,
                message: error.message
            });
        } else if (error.message === '无权限删除此视频') {
            res.status(403).json({
                code: STATUS_CODES.FORBIDDEN.code,
                message: error.message
            });
        } else {
            res.status(500).json({
                code: STATUS_CODES.SERVER_ERROR.code,
                message: '删除视频失败',
                error: error.message
            });
        }
    }
});

// 获取热门视频
router.get('/popular', async (req, res) => {
    try {
        const { timeRange = '7d', limit = 20, category } = req.query;
        
        const result = await videoAPI.getPopularVideos({
            timeRange,
            limit: parseInt(limit),
            category
        });
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '获取热门视频成功',
            data: result
        });
    } catch (error) {
        console.error('获取热门视频失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR,
            message: '获取热门视频失败',
            error: error.message
        });
    }
});

// 获取用户视频列表
router.get('/user/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { page = 1, limit = 20, viewerId } = req.query;
        
        if (!userId) {
            return res.status(400).json({
                code: STATUS_CODES.PARAM_ERROR,
                message: '用户ID不能为空'
            });
        }
        
        const result = await videoAPI.getUserVideos({
            userId,
            page: parseInt(page),
            limit: parseInt(limit),
            viewerId
        });
        
        res.json({
            code: STATUS_CODES.SUCCESS,
            message: '获取用户视频列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取用户视频列表失败:', error);
        res.status(500).json({
            code: STATUS_CODES.SERVER_ERROR,
            message: '获取用户视频列表失败',
            error: error.message
        });
    }
});

module.exports = router;